package com.mofum.cloud.core.handler.impl;

import com.mofum.cloud.core.error.ins.InstructionNotFoundException;
import com.mofum.cloud.core.error.ins.InstructionRegisterException;
import com.mofum.cloud.core.handler.InstructionsHandlerPool;
import com.mofum.cloud.core.model.Algorithm;
import com.mofum.cloud.core.model.Instruction;

import java.math.BigInteger;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 指令操作池适配器
 * ===================================================================
 * <p> 指令操作池适配器让其具备指令操作池的基本功能
 * ===================================================================
 *
 * @author yumi@omuao.com
 */
public class InstructionsHandlerPoolAdapter implements InstructionsHandlerPool {

    /**
     * 指令操作池
     */
    private static final Map<BigInteger, Instruction> HANDLER_POOL = new ConcurrentHashMap<>();

    @Override
    public void registerInstruction(Instruction instruction) throws InstructionRegisterException {
        boolean flag = registerIns(instruction);
        if (!flag) {
            throw new InstructionRegisterException("Instruction unregistered!");
        }
    }

    @Override
    public boolean registerIns(Instruction instruction) {
        //指令ID
        BigInteger id = instruction.getId();
        if (id == null) {
            return false;
        }

        //算法
        Algorithm algorithm = instruction.getAlgorithm();
        if (algorithm == null) {
            return false;
        }

        HANDLER_POOL.put(id, instruction);
        return true;
    }

    @Override
    public Instruction findInstructionById(BigInteger commandId) throws InstructionNotFoundException {
        if (commandId == null) {
            throw new InstructionNotFoundException("Instruction id not set!");
        }

        Instruction instruction = HANDLER_POOL.get(commandId);
        if (instruction == null) {
            throw new InstructionNotFoundException("Instruction not found!");
        }
        return instruction;
    }
}
